package com.qiantu.phone.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.db.LLSourceHomepageDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SourceHomepageBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.event.DeviceListChangeEvent;
import com.qiantu.phone.event.DeviceLocalChangeEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.adapter.HomeSceneDeviceAdapter;
import com.qiantu.phone.widget.HomeTopSceneView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * time   : 2021/12/22
 */
public final class HomeSubFragment extends AppFragment<AppActivity> {

    /**
     * 0 默认 1常用 2通用
     */
    private int type;
    private String roomSerialNo;
    private Handler mHandler;
    private boolean isFirst = true;

    public static HomeSubFragment newInstance(String roomSerialNo, int type) {
        HomeSubFragment fragment = new HomeSubFragment();
        fragment.setType(type);
        fragment.setRoomSerialNo(roomSerialNo);
        Bundle bundle = new Bundle();
        bundle.putString("roomSerialNo", roomSerialNo);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }
    private RecyclerView mRecyclerView;
    private HomeSceneDeviceAdapter mHomeSceneDeviceAdapter;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getRoomSerialNo() {
        return roomSerialNo;
    }

    public void setRoomSerialNo(String roomSerialNo) {
        this.roomSerialNo = roomSerialNo;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_sub_fragment;
    }

    @Override
    protected void initView() {
        type = getInt("type");
        roomSerialNo = getString("roomSerialNo");
        EventBus.getDefault().register(this);
//        mRefreshLayout = findViewById(R.id.rl_status_refresh);
//        mStatusLayout = findViewById(R.id.status_layout);
        mRecyclerView = findViewById(R.id.recycler_view);
//        mStatusLayout.setBackground(((HomeFragment)getParentFragment()).getViewPagerBackground());

        SimpleItemAnimator sa = (SimpleItemAnimator) mRecyclerView.getItemAnimator();
        sa.setSupportsChangeAnimations(false);
        mRecyclerView.setItemAnimator(null);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mHomeSceneDeviceAdapter = new HomeSceneDeviceAdapter(null, type, roomSerialNo);
        mHomeSceneDeviceAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mHomeSceneDeviceAdapter);
        Method checkForGapsMethod = null;
        try {
            checkForGapsMethod = StaggeredGridLayoutManager.class.getDeclaredMethod("checkForGaps");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        checkForGapsMethod.setAccessible(true);
        Method finalCheckForGapsMethod = checkForGapsMethod;
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (finalCheckForGapsMethod != null) {
                    try {
                        finalCheckForGapsMethod.invoke(layoutManager);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
//        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mHomeSceneDeviceAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                scrollTo(position);
                if (mHandler == null) {
                    mHandler = new Handler();
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int[] outLocation = new int[2];
                        view.getLocationOnScreen(outLocation);
                        DeviceBean device = mHomeSceneDeviceAdapter.getData().get(position);
                        ((HomeActivity) getActivity()).longClickDeviceItem(outLocation[0], outLocation[1], view.getWidth(), view.getHeight(), device, type == 1);
                    }
                }, 50);

                return true;
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                ((HomeActivity) getActivity()).hideLongClickFloatView();

            }
        });
    }

    public void scrollTo(int position) {
        if (mRecyclerView != null) {
            mRecyclerView.scrollToPosition(position);
//            ((HomeFragment)getParentFragment()).setAppBarLayoutOffset();
        }
    }

    @Override
    protected void initData() {
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = getDevices(0);
                //添加头场景
                DeviceBean topScene = new DeviceBean();
                List<SceneBean> scenes = null;
                switch (type) {
                    case 0:
                        scenes = LLSceneDBManager.getInstance(getContext()).getSceneByRoom(roomSerialNo);
                        break;
                    case 1:
                        scenes = LLSceneDBManager.getInstance(getContext()).getFavouriteScenes();
                        break;
                    case 2:
                        scenes = LLSceneDBManager.getInstance(getContext()).getCommonScenes();
                        break;
                }
                List<SceneBean> showScene = new ArrayList<>();
                for(int i = 0;i < scenes.size();i++){
                    if(i >= 6){
                        break;
                    }
                    showScene.add(scenes.get(i));
                }
                topScene.setHomeScenes(showScene);
                DeviceBean topEnviroment = new DeviceBean();
                topEnviroment.setHomeEnviroments(getEnvironment());
                List<DeviceBean> data = new ArrayList<>();
                data.add(topEnviroment);
                data.add(topScene);
                if (devices != null && devices.size() > 0) {
                    data.addAll(devices);
                } else {
                    DeviceBean emptyDevice = new DeviceBean();
                    data.add(emptyDevice);
                }
                emitter.onNext(data);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> data) throws Exception {
                        mHomeSceneDeviceAdapter.setNewInstance(data);
//                        showComplete();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    public void updateTop(int marginTop) {
        //常用，通用没有楼层不需要更新
        if (type == 1 || type == 2 || !((HomeFragment) getParentFragment()).hasFloor()) {
            return;
        }
        if (mRecyclerView.getChildCount() > 0) {
            View topView = mRecyclerView.getChildAt(0);
            if (topView != null && topView instanceof HomeTopSceneView) {
                StaggeredGridLayoutManager.LayoutParams sl = (StaggeredGridLayoutManager.LayoutParams) topView.getLayoutParams();
                if (sl != null && sl.topMargin != marginTop) {
                    sl.topMargin = marginTop;
                }
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            updateTop(((HomeFragment) getParentFragment()).getSubFragmentTop());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceChangeEvent(DeviceItemChangeEvent event) {
        updateDevice(event.roomSerialNo, event.deviceSerialNo, event.isFavourite);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceListChangeEvent(DeviceListChangeEvent event) {
        updateDevices(event.deviceSerialNos);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceLocalChangeEvent(DeviceLocalChangeEvent event) {
        updateDevice(event.roomSerialNo, event.deviceSerialNo, event.isFavourite);
    }

    private void updateDevice(String roomSerialNo, String deviceSerialNo, boolean isFavourite) {
        //判断房间是否跟设备所在房间才更新
        if (!TextUtils.isEmpty(deviceSerialNo)) {
            DeviceBean device = null;
            switch (type) {
                case 0://0 默认
                    if(this.roomSerialNo.equals(roomSerialNo)){
                        device = LLDeviceDBManager.getInstance(getContext()).getAvailableDeviceByRoomSerialNoAndSerialNo(this.roomSerialNo, deviceSerialNo);
                        //查询后，没有设备关闭设备弹框
//                        if(device == null){
//                            ((HomeActivity)getActivity()).hideDeviceView();
//                        }
                    }
                    break;
                case 1:// 1常用
                        device = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(deviceSerialNo);
                        //查询后，没有设备关闭设备弹框
//                        if(device == null){
//                            ((HomeActivity)getActivity()).hideDeviceView();
//                        }
                    break;
                case 2:// 2通用
                    if(RoomBean.ROOM_COMMON_SERIALNO.equals(roomSerialNo)){
                        device = LLDeviceDBManager.getInstance(getContext()).getAvailableCommonDeviceBySerialNo(deviceSerialNo);
                        //查询后，没有设备关闭设备弹框
//                        if(device == null){
//                            ((HomeActivity)getActivity()).hideDeviceView();
//                        }
                    }
                    break;
            }
            if (device != null) {
                mHomeSceneDeviceAdapter.update(device);
            }
        }
    }

    private void updateDevices(List<String> deviceSerialNos) {
        //判断房间是否跟设备所在房间才更新
        if (deviceSerialNos != null && deviceSerialNos.size() > 0) {
            List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesByDeviceSerialNos(deviceSerialNos);
            //查询后，没有设备关闭设备弹框
            if(devices == null || devices.size() == 0){
//                ((HomeActivity)getActivity()).hideDeviceView();
            }else{
                mHomeSceneDeviceAdapter.update(devices);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshDeviceListEvent(RefreshDeviceListEvent event) {
//        if(event.isAll
//                || (type == 0 && roomSerialNo.equals(event.roomSerialNo))
//                || (type == 1 && event.isFavourite)
//                || (type == 2 && RoomBean.ROOM_COMMON_SERIALNO.equals(roomSerialNo))){
//            Log.i("luzx", "onRefreshDeviceListEvent");
            initData();
//        }
    }

    private List<DeviceBean> getDevices(int isEnviroment) {
        List<DeviceBean> devices = null;
        switch (type) {
            case 0:
                devices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableDeviceByRoom(roomSerialNo);
                break;
            case 1:
                devices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableFavouriteDevices();
//                List<DeviceBean> commandDevices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableCommonDevices();
//                List<DeviceBean> newDevices = new ArrayList<>();
//                for(DeviceBean commandDevice : commandDevices){
//                    if(commandDevice.getDeviceType().equals("tctdl") && commandDevice.getDeviceGroup() == 0 && !commandDevice.getIsFavourite()){
//                        continue;
//                    }
//                    newDevices.add(commandDevice);
//                }
//                devices.addAll(newDevices);
                break;
            case 2:
                devices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableCommonDevices();
                break;
        }
        return devices;
    }

    private List<DeviceBean> getEnvironment() {
        List<DeviceBean> devices = new ArrayList<>();
//        List<SourceHomepageBean> homepages = new ArrayList<>();
//        switch (type) {
//            case 0:
//                homepages = LLSourceHomepageDBManager.getInstance(getContext()).getDataByRoomSerialNo(roomSerialNo);
//                break;
//        }
//        for(int i = 0;i < homepages.size();i++){
//            SourceHomepageBean bean = homepages.get(i);
//            List<DeviceBean> deviceBeans = bean.getDevices();
//            if(deviceBeans.size() != 0){
//                devices.add(deviceBeans.get(0));
//            }
//
//        }
        return devices;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshSceneEvent(RefreshSceneEvent event) {
//        if(event.isAll
//            || (type == 0 && roomSerialNo.equals(event.roomSerialNo))
//            || (type == 1 && event.isFavourite)
//            || (type == 2 && RoomBean.ROOM_COMMON_SERIALNO.equals(roomSerialNo))){
            //刷新顶部场景
            Map<Integer, Object> payload = new HashMap<>();
            payload.put(HomeSceneDeviceAdapter.TYPE_PAYLOAD_REFRESH_SCENE, null);
            mHomeSceneDeviceAdapter.notifyItemChanged(0, payload);
//        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

//    @Override
//    public StatusLayout getStatusLayout() {
//        return mStatusLayout;
//    }

    //    @Override
//    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.clearData();
////            mAdapter.setData(analogData());
//            mRefreshLayout.finishRefresh();
//        }, 1000);
//    }
//
//    @Override
//    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.addData(analogData());
//            mRefreshLayout.finishLoadMore();
//
//            mAdapter.setLastPage(mAdapter.getCount() >= 100);
//            mRefreshLayout.setNoMoreData(mAdapter.isLastPage());
//        }, 1000);
//    }
}